import React, { useState, useMemo } from 'react';
import { Modal, Input, Select, Tabs, Card, Row, Col, Empty, Spin } from 'antd';
import type { ModalProps } from 'antd';
import * as AntdIcons from '@ant-design/icons';
import { SearchOutlined } from '@ant-design/icons';
import './IconSelect.css';

const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

// 图标分类
const iconCategories = [
  {
    name: '方向性图标',
    icons: [
      'StepBackwardOutlined', 'StepForwardOutlined', 'FastBackwardOutlined', 'FastForwardOutlined',
      'ShrinkOutlined', 'ArrowsAltOutlined', 'DownOutlined', 'UpOutlined', 'LeftOutlined',
      'RightOutlined', 'CaretUpOutlined', 'CaretDownOutlined', 'CaretLeftOutlined', 'CaretRightOutlined',
      'UpCircleOutlined', 'DownCircleOutlined', 'LeftCircleOutlined', 'RightCircleOutlined',
      'DoubleLeftOutlined', 'DoubleRightOutlined', 'VerticalLeftOutlined', 'VerticalRightOutlined',
      'VerticalAlignTopOutlined', 'VerticalAlignMiddleOutlined', 'VerticalAlignBottomOutlined',
      'ForwardOutlined', 'BackwardOutlined', 'RollbackOutlined', 'EnterOutlined',
      'RetweetOutlined', 'SwapOutlined', 'SwapLeftOutlined', 'SwapRightOutlined',
      'ArrowUpOutlined', 'ArrowDownOutlined', 'ArrowLeftOutlined', 'ArrowRightOutlined',
      'PlayCircleOutlined', 'UpSquareOutlined', 'DownSquareOutlined', 'LeftSquareOutlined', 'RightSquareOutlined',
      'LoginOutlined', 'LogoutOutlined', 'MenuFoldOutlined', 'MenuUnfoldOutlined',
      'BorderOutlined', 'PicCenterOutlined', 'PicLeftOutlined', 'PicRightOutlined',
    ]
  },
  {
    name: '提示性图标',
    icons: [
      'QuestionCircleOutlined', 'PlusCircleOutlined', 'PlusOutlined', 'InfoCircleOutlined',
      'ExclamationCircleOutlined', 'CloseCircleOutlined', 'CloseOutlined', 'CheckCircleOutlined',
      'CheckOutlined', 'ClockCircleOutlined', 'WarningOutlined', 'IssuesCloseOutlined',
      'StopOutlined', 'EditOutlined', 'CopyOutlined', 'ScissorOutlined',
      'DeleteOutlined', 'SnippetsOutlined', 'DiffOutlined', 'HighlightOutlined',
      'AlignCenterOutlined', 'AlignLeftOutlined', 'AlignRightOutlined', 'BgColorsOutlined',
      'BoldOutlined', 'ItalicOutlined', 'UnderlineOutlined', 'StrikethroughOutlined',
      'RedoOutlined', 'UndoOutlined', 'ZoomInOutlined', 'ZoomOutOutlined',
      'FolderOpenOutlined', 'FolderViewOutlined', 'FileAddOutlined', 'DraggerOutlined',
      'FormOutlined', 'ReadOutlined', 'ExceptionOutlined', 'FileOutlined',
      'FileTextOutlined', 'FileUnknownOutlined', 'FilePdfOutlined', 'FileWordOutlined',
      'FileExcelOutlined', 'FileJpgOutlined', 'FilePptOutlined', 'FileMarkdownOutlined',
      'FileImageOutlined', 'FileZipOutlined', 'FileGifOutlined',
    ]
  },
  {
    name: '通用图标',
    icons: [
      'StarOutlined', 'HeartOutlined', 'EnvironmentOutlined', 'HomeOutlined',
      'LoadingOutlined', 'Loading3QuartersOutlined', 'SmileOutlined', 'DashboardOutlined',
      'NotificationOutlined', 'MailOutlined', 'HighlightOutlined', 'AudioOutlined',
      'BellOutlined', 'BulbOutlined', 'ThunderboltOutlined', 'CrownOutlined',
      'CustomerServiceOutlined', 'FireOutlined', 'DollarOutlined', 'GiftOutlined',
      'HddOutlined', 'KeyOutlined', 'LikeOutlined', 'LockOutlined',
      'MobileOutlined', 'NotificationOutlined', 'PayCircleOutlined', 'PieChartOutlined',
      'PropertySafetyOutlined', 'ReconciliationOutlined', 'RestOutlined', 'SafetyOutlined',
      'SaveOutlined', 'ScheduleOutlined', 'SettingOutlined', 'ShoppingOutlined',
      'SoundOutlined', 'TeamOutlined', 'ToTopOutlined', 'ToolOutlined',
      'TrademarkCircleOutlined', 'UnlockOutlined', 'UsbOutlined', 'VideoCameraOutlined',
      'WifiOutlined', 'ApartmentOutlined', 'AudiobookOutlined', 'BankOutlined',
      'BookOutlined', 'BorderlessTableOutlined', 'CalculatorOutlined', 'CalendarOutlined',
      'CameraOutlined', 'CarOutlined', 'CarryOutOutlined', 'CiCircleOutlined',
      'CloudOutlined', 'ClusterOutlined', 'CodeOutlined', 'CoffeeOutlined',
      'CompassOutlined', 'ContactsOutlined', 'ContainerOutlined', 'ControlOutlined',
      'CopyrightOutlined', 'CreditCardOutlined', 'CrownOutlined', 'CustomerServiceOutlined',
      'DashboardOutlined', 'DatabaseOutlined', 'DeleteRowOutlined', 'DeliveredProcedureOutlined',
      'DeploymentUnitOutlined', 'DesktopOutlined', 'DingtalkOutlined', 'DisconnectOutlined',
      'DisplayOutlined', 'DollarCircleOutlined', 'DownloadOutlined', 'DragOutlined',
      'EllipsisOutlined', 'EnvironmentOutlined', 'EuroCircleOutlined', 'ExclamationOutlined',
      'EyeOutlined', 'EyeInvisibleOutlined', 'FacebookOutlined', 'FallOutlined',
      'FastForwardOutlined', 'FieldBinaryOutlined', 'FieldNumberOutlined', 'FieldStringOutlined',
      'FieldTimeOutlined', 'FileDoneOutlined', 'FileExclamationOutlined', 'FileExclOutlined',
      'FileProtectOutlined', 'FileSearchOutlined', 'FileSyncOutlined', 'FilterOutlined',
      'FireOutlined', 'FlagOutlined', 'FolderAddOutlined', 'FolderOutlined',
      'FormatPainterOutlined', 'ForkOutlined', 'FormOutlined', 'ForwardOutlined',
      'FrownOutlined', 'FullscreenOutlined', 'FullscreenExitOutlined', 'FunctionOutlined',
      'FundOutlined', 'FundProjectionScreenOutlined', 'FundViewOutlined', 'FunnelPlotOutlined',
      'GatewayOutlined', 'GifOutlined', 'GiftOutlined', 'GlobalOutlined',
      'GoldOutlined', 'GoldenOutlined', 'GoogleOutlined', 'GroupOutlined',
      'HddOutlined', 'HeartOutlined', 'HeatMapOutlined', 'HistoryOutlined',
      'HolderOutlined', 'HomeOutlined', 'HourglassOutlined', 'IdcardOutlined',
      'IeOutlined', 'ImportOutlined', 'InboxOutlined', 'InsertRowAboveOutlined',
      'InsertRowBelowOutlined', 'InsertRowLeftOutlined', 'InsertRowRightOutlined',
      'InstagramOutlined', 'InsuranceOutlined', 'InteractionOutlined', 'KeyOutlined',
      'LaptopOutlined', 'LayoutOutlined', 'LeftOutlined', 'LikeOutlined',
      'LineOutlined', 'LineChartOutlined', 'LinkOutlined', 'LinkedinOutlined',
      'LoadingOutlined', 'LockOutlined', 'MailOutlined', 'ManOutlined',
      'MedicineBoxOutlined', 'MehOutlined', 'MenuOutlined', 'MergeCellsOutlined',
      'MessageOutlined', 'MinusCircleOutlined', 'MinusOutlined', 'MobileOutlined',
      'MoneyCollectOutlined', 'MonitorOutlined', 'MoreOutlined', 'NodeCollapseOutlined',
      'NodeExpandOutlined', 'NodeIndexOutlined', 'NotificationOutlined', 'NumberOutlined',
      'OneToOneOutlined', 'OrderedListOutlined', 'PaperClipOutlined', 'PartitionOutlined',
      'PauseOutlined', 'PayCircleOutlined', 'PercentageOutlined', 'PhoneOutlined',
      'PictureOutlined', 'PieChartOutlined', 'PoundCircleOutlined', 'PoundOutlined',
      'PoweroffOutlined', 'PrinterOutlined', 'ProfileOutlined', 'ProjectOutlined',
      'PropertySafetyOutlined', 'PullRequestOutlined', 'PushpinOutlined', 'QqOutlined',
      'QrcodeOutlined', 'QuestionOutlined', 'QuestionCircleOutlined', 'RadiusSettingOutlined',
      'RadiusUpleftOutlined', 'RadiusUprightOutlined', 'ReadOutlined', 'ReconciliationOutlined',
      'RedEnvelopeOutlined', 'RedditOutlined', 'RedoOutlined', 'ReloadOutlined',
      'RestOutlined', 'RetweetOutlined', 'RightOutlined', 'RightCircleOutlined',
      'RobotOutlined', 'RocketOutlined', 'SafetyCertificateOutlined', 'SafetyOutlined',
      'SaveOutlined', 'ScanOutlined', 'ScheduleOutlined', 'SearchOutlined',
      'SecurityScanOutlined', 'SelectOutlined', 'SettingOutlined', 'ShakeOutlined',
      'ShareAltOutlined', 'ShopOutlined', 'ShoppingCartOutlined', 'ShoppingOutlined',
      'SisternodeOutlined', 'SkinOutlined', 'SmileOutlined', 'SolutionOutlined',
      'SoundOutlined', 'SplitCellsOutlined', 'StarOutlined', 'SubnodeOutlined',
      'SwitcherOutlined', 'SyncOutlined', 'TableOutlined', 'TabletOutlined',
      'TagOutlined', 'TagsOutlined', 'TaobaoOutlined', 'ThunderboltOutlined',
      'ToTopOutlined', 'ToolOutlined', 'TrademarkCircleOutlined', 'TrademarkOutlined',
      'TransactionOutlined', 'TranslationOutlined', 'TwitterOutlined', 'UnderlineOutlined',
      'UndoOutlined', 'UnlockOutlined', 'UnorderedListOutlined', 'UpOutlined',
      'UploadOutlined', 'UserOutlined', 'UsergroupAddOutlined', 'UsergroupDeleteOutlined',
      'UserSwitchOutlined', 'VerifiedOutlined', 'VideoCameraAddOutlined', 'VideoCameraOutlined',
      'WalletOutlined', 'WarningOutlined', 'WechatOutlined', 'WeiboOutlined',
      'WhatsAppOutlined', 'WifiOutlined', 'WindowsOutlined', 'WomanOutlined',
      'YahooOutlined', 'YoutubeOutlined', 'YuqueOutlined', 'ZhihuOutlined',
      'ZoomInOutlined', 'ZoomOutOutlined', 'AddOutlined', 'AppstoreOutlined',
    ]
  },
  {
    name: '品牌图标',
    icons: [
      'AlipayOutlined', 'AlipayCircleOutlined', 'TaobaoOutlined', 'TaobaoCircleOutlined',
      'AmazonOutlined', 'AmazonCircleOutlined', 'AndroidOutlined', 'AppleOutlined',
      'BehanceOutlined', 'BehanceSquareOutlined', 'DribbbleOutlined', 'DribbbleSquareOutlined',
      'DropboxOutlined', 'DropboxCircleOutlined', 'EnvatoOutlined', 'EnvatoSquareOutlined',
      'FacebookOutlined', 'FacebookFilled', 'FigmaOutlined', 'FirebaseOutlined',
      'GithubOutlined', 'GitlabOutlined', 'GoogleOutlined', 'GooglePlusOutlined',
      'GooglePlusSquareOutlined', 'InstagramOutlined', 'InstagramFilled', 'LinkedinOutlined',
      'MediumOutlined', 'MediumSquareOutlined', 'MicrosoftOutlined', 'PaypalOutlined',
      'PinterestOutlined', 'PinterestSquareOutlined', 'QqOutlined', 'QqSquareOutlined',
      'RedditOutlined', 'RedditSquareOutlined', 'SkypeOutlined', 'SlackOutlined',
      'SnapchatOutlined', 'SnapchatSquareOutlined', 'SoundcloudOutlined', 'SpotifyOutlined',
      'TelegramOutlined', 'TikTokOutlined', 'TwitterOutlined', 'TwitterSquareOutlined',
      'VimeoOutlined', 'VimeoSquareOutlined', 'VkOutlined', 'WechatOutlined',
      'WechatFilled', 'WeiboOutlined', 'WhatsappOutlined', 'WindowsOutlined',
      'XOutlined', 'YahooOutlined', 'YoutubeOutlined', 'YoutubeFilled',
      'ZhihuOutlined', 'ZhihuSquareOutlined', 'AlipaySquareFilled', 'AmazonSquareFilled',
      'AppleFilled', 'BehanceSquareFilled', 'DribbbleSquareFilled', 'DropboxSquareFilled',
      'EnvatoSquareFilled', 'FacebookFilled', 'FigmaFilled', 'FirebaseFilled',
      'GithubFilled', 'GitlabFilled', 'GoogleFilled', 'GooglePlusSquareFilled',
      'InstagramFilled', 'LinkedinFilled', 'MediumSquareFilled', 'MicrosoftFilled',
      'PaypalFilled', 'PinterestSquareFilled', 'QqSquareFilled', 'RedditSquareFilled',
      'SkypeFilled', 'SlackFilled', 'SnapchatSquareFilled', 'SoundcloudFilled',
      'SpotifyFilled', 'TelegramFilled', 'TikTokFilled', 'TwitterFilled',
      'TwitterSquareFilled', 'VimeoFilled', 'VimeoSquareFilled', 'VkFilled',
      'WechatFilled', 'WeiboFilled', 'WhatsappFilled', 'WindowsFilled',
      'XFilled', 'YahooFilled', 'YoutubeFilled', 'ZhihuSquareFilled',
    ]
  }
];

interface IconSelectProps {
  value?: string;
  onChange?: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  allowClear?: boolean;
  style?: React.CSSProperties;
  size?: 'small' | 'middle' | 'large';
}

interface IconSelectModalProps extends ModalProps {
  visible: boolean;
  onSelect: (icon: string) => void;
  onCancel: () => void;
  currentIcon?: string;
}

// 图标选择模态框组件
const IconSelectModal: React.FC<IconSelectModalProps> = ({
  visible,
  onSelect,
  onCancel,
  currentIcon,
  ...modalProps
}) => {
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('0');

  // 过滤图标
  const filteredIcons = useMemo(() => {
    if (!searchText) return iconCategories;

    return iconCategories.map(category => ({
      name: category.name,
      icons: category.icons.filter(icon =>
        icon.toLowerCase().includes(searchText.toLowerCase())
      )
    })).filter(category => category.icons.length > 0);
  }, [searchText]);

  // 渲染图标卡片
  const renderIconCards = (icons: string[]) => {
    const IconComponent = (iconName: string) => {
      const Icon = (AntdIcons as any)[iconName];
      if (!Icon) return null;

      return (
        <Card
          key={iconName}
          className={`icon-card ${currentIcon === iconName ? 'selected' : ''}`}
          hoverable
          onClick={() => onSelect(iconName)}
        >
          <div className="icon-container">
            <Icon />
          </div>
          <div className="icon-name">
            {iconName.replace('Outlined', '').replace('Filled', '')}
          </div>
        </Card>
      );
    };

    return (
      <div className="icon-grid">
        {icons.map(IconComponent)}
      </div>
    );
  };

  return (
    <Modal
      title="选择图标"
      width={800}
      bodyStyle={{ padding: '20px' }}
      visible={visible}
      onCancel={onCancel}
      footer={null}
      {...modalProps}
    >
      <Search
        placeholder="搜索图标..."
        allowClear
        style={{ marginBottom: '20px' }}
        onChange={(e) => setSearchText(e.target.value)}
        prefix={<SearchOutlined />}
      />

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        {filteredIcons.map((category, index) => (
          <TabPane tab={category.name} key={index.toString()}>
            {category.icons.length > 0 ? (
              renderIconCards(category.icons)
            ) : (
              <Empty description="没有找到匹配的图标" />
            )}
          </TabPane>
        ))}
      </Tabs>
    </Modal>
  );
};

// 图标选择器组件
const IconSelect: React.FC<IconSelectProps> = ({
  value,
  onChange,
  placeholder = '请选择图标',
  disabled = false,
  allowClear = true,
  style,
  size = 'middle'
}) => {
  const [modalVisible, setModalVisible] = useState(false);

  const handleSelect = (icon: string) => {
    onChange?.(icon);
    setModalVisible(false);
  };

  const handleClear = () => {
    onChange?.('');
  };

  // 获取当前图标组件
  const renderCurrentIcon = () => {
    if (!value) return null;

    const Icon = (AntdIcons as any)[value];
    if (!Icon) return null;

    return (
      <span style={{ marginRight: '8px', verticalAlign: 'middle' }}>
        <Icon />
      </span>
    );
  };

  return (
    <>
      <div style={{ display: 'flex', alignItems: 'center', ...style }}>
        <Input
          value={value}
          onChange={(e) => onChange?.(e.target.value)}
          placeholder={placeholder}
          disabled={disabled}
          readOnly
          addonBefore={renderCurrentIcon()}
          addonAfter={
            <div style={{ display: 'flex', alignItems: 'center' }}>
              {value && allowClear && (
                <span
                  style={{
                    cursor: 'pointer',
                    marginRight: '8px',
                    color: '#999',
                    fontSize: '12px'
                  }}
                  onClick={handleClear}
                >
                  清除
                </span>
              )}
              <span
                style={{
                  cursor: disabled ? 'not-allowed' : 'pointer',
                  color: disabled ? '#999' : '#1890ff',
                  fontSize: '12px'
                }}
                onClick={() => !disabled && setModalVisible(true)}
              >
                选择
              </span>
            </div>
          }
          size={size}
        />
      </div>

      <IconSelectModal
        visible={modalVisible}
        onSelect={handleSelect}
        onCancel={() => setModalVisible(false)}
        currentIcon={value}
        destroyOnClose
      />
    </>
  );
};

export default IconSelect;